package com.example.demo.service;

import com.example.demo.config.HuaweiIoTConfig;
import com.example.demo.model.DeviceData;
import com.huaweicloud.sdk.core.auth.BasicCredentials;
import com.huaweicloud.sdk.core.http.HttpConfig;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.ShowDeviceRequest;
import com.huaweicloud.sdk.iotda.v5.model.ShowDeviceResponse;
import org.springframework.stereotype.Service;
import com.huaweicloud.sdk.iotda.v5.model.DeviceProperties;
import javax.annotation.Resource;
import javax.persistence.EntityManager;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.huaweicloud.sdk.iotda.v5.*;

@Service
public class HuaweiIoTService {
    @Resource
    private HuaweiIoTConfig config;
    @Resource
    private EntityManager entityManager;

    public IoTDAClient createClient() {
        HttpConfig httpConfig = HttpConfig.getDefaultHttpConfig()
                .withTimeout(config.getTimeout());
        BasicCredentials credentials = new BasicCredentials()
                .withAk(config.getAk())
                .withSk(config.getSk())
                .withProjectId(config.getProjectId());
        return IoTDAClient.newBuilder()
                .withCredential(credentials)
                .withHttpConfig(httpConfig)
                .withEndpoint(config.getEndpoint())
                .build();
    }

    public void processDeviceData(String deviceId, Map<String, Object> data) {
        DeviceData entity = new DeviceData();
        entity.setDeviceId(deviceId);

        // 安全获取数据（假设温湿度字段名为temperature/humidity）
        if (data.containsKey("temperature")) {
            entity.setTemperature(Double.parseDouble(data.get("temperature").toString()));
        }
        if (data.containsKey("humidity")) {
            entity.setHumidity(Double.parseDouble(data.get("humidity").toString()));
        }
        entity.setReportTime(new Date());

        // 使用JPA保存
        entityManager.persist(entity);
    }

    public void fetchAndSaveDeviceData(String deviceId) {
        IoTDAClient client = createClient();
        ShowDeviceRequest request = new ShowDeviceRequest().withDeviceId(deviceId);
        try {
            ShowDeviceResponse response = client.showDevice(request);

            // 调试：打印完整响应
            System.out.println("DEBUG Response: " + response.toString());

            // 正确获取设备属性（根据官方文档调整）
            Map<String, DeviceProperties> properties = response.getProperties();
            if (properties != null) {
                Map<String, Object> data = new HashMap<>();
                properties.forEach((key, prop) -> {
                    data.put(key, prop.getValue()); // 提取属性值
                });
                processDeviceData(deviceId, data);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}